package cn.iocoder.yudao.module.famous.doctor.controller.app.operator.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import org.springframework.util.StringUtils;

import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;
import java.util.List;

/**
 * @author sun 2020/6/3 21:45
 */
public class FileUtil {

    private FileUtil() {
    }

    /**
     * 去除掉域名
     * 获取文件名用来存储,节省空间
     */
    public static String getShortFileName(String fullFileName) {
        return StringUtils.isEmpty(fullFileName) ? null : fullFileName.substring(fullFileName.lastIndexOf("/") + 1);
    }

    /**
     * 根据json数组获取文件名
     */
    public static String getShortFileNameByJsonArray(String jsonArr) {
        if (!StringUtils.isEmpty(jsonArr)) {
            StringBuilder sb = new StringBuilder();
            JSONArray jsonArray = JSON.parseArray(jsonArr);
            for (int i = 0, len = jsonArray.size(); i < len; i++) {
                sb.append(FileUtil.getShortFileName(jsonArray.getString(i))).append(",");
            }
            String finalStr = sb.toString();
            // 去除掉最后的逗号
            return finalStr.substring(0, finalStr.length() - 1);
        }
        return null;
    }

    /**
     * 根据逗号分隔字符串获取文件名
     */
    public static String getShortFileNameByStrArray(String strArr) {
        if (!StringUtils.isEmpty(strArr)) {
            StringBuilder sb = new StringBuilder();
            Arrays.stream(strArr.split(",")).forEach(s -> sb.append(FileUtil.getShortFileName(s)).append(","));
            String finalStr = sb.toString();
            // 去除掉最后的逗号
            return finalStr.substring(0, finalStr.length() - 1);
        }
        return null;
    }


    public static String getShortFileNameByList(List<String> fileList) {
        if (fileList == null || fileList.size() == 0) {
            return null;
        }
        StringBuilder sb = new StringBuilder();
        fileList.forEach(fileName -> {
            sb.append(getShortFileName(fileName)).append(",");
        });
        String finalStr = sb.toString();
        // 去除掉最后的逗号
        return finalStr.substring(0, finalStr.length() - 1);
    }


    /**
     * 抓取网上的图片
     */
    public static InputStream getFileInputStream(String imgUrl) {
        try {
            URL url = new URL(imgUrl);
            URLConnection conn = url.openConnection();
            conn.setConnectTimeout(3 * 1000);
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            return conn.getInputStream();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}
